﻿using System;
using System.Drawing;
using System.Dynamic;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using AL.ViewModel;
using Codeplex.Data;
using mshtml;
using System.Text;
using Newtonsoft.Json;

namespace AL.Helper
{
    public class LoginHelper
    {

        private static DateTime _updateAuthTime = DateTime.Now;
        public static bool Authorization(AccountModel account)
        {
            if (!account.IsLogined)
            {
                MessageBox.Show(@"用户未登录");
                return false;
            }

            if (_updateAuthTime < DateTime.Now)
            {
                try
                {
                    // TODO: 用户远程鉴权
                    var webClient = new WebClient();
                    webClient.Encoding = Encoding.UTF8;
                    webClient.Headers.Add("Accept: text/html, application/xhtml+xml, */*");
                    webClient.Headers.Add(
                        "User-Agent: Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25");
                    webClient.Headers.Add("Cache-Control: no-cache");
                    string url =
                        string.Format(
                            "http://www.carloschen.cn/cotipapp/co_wx_index.php/WXSearch/verify?userName={0}&&nickName={1}",
                            account.UserName, account.NickName);
                    string content = webClient.DownloadString(url);
                    var result = DynamicJson.Parse(content);
                    if (result.success != "1")
                    {
                        MessageBox.Show(result.msg);
                        return false;
                    }
                    else
                    {
                        _updateAuthTime = DateTime.Now.AddMinutes(10);
                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return false;
                }
            }

            return true;
        }

        //private static DateTime _updateCookieTime = DateTime.Now.AddDays(1);
        public static String GetCookieString(WebBrowser browser)
        {
            var cookieString = string.Empty;

            var htmlDocument = browser.Document;
            if (htmlDocument != null) cookieString = htmlDocument.Cookie;

            if(string.IsNullOrWhiteSpace(cookieString)) MessageBox.Show(@"cookie 为空，请重新登录");
            return cookieString;
        }

        public static AccountModel CheckLogin(WebBrowser browser)
        {
            var accountModel = new AccountModel();
            var htmlDocument = browser.Document;

            if (htmlDocument == null){ return accountModel; }

            var profileElement = htmlDocument.GetElementById("profile");
            if (profileElement == null){ return accountModel; }

            accountModel.LoginCookies = htmlDocument.Cookie;

            var pat = "wxuin=(?<WXUIN>[^;]*);";
            var mat = Regex.Match(accountModel.LoginCookies, pat);
            if (mat.Success) accountModel.UserName = mat.Groups["WXUIN"].Value;

            accountModel.Host = string.Format("{0}://{1}", browser.Url.Scheme, browser.Url.Host);

            accountModel.IsLogined = false;
            foreach (HtmlElement item in profileElement.All)
            {
                var tagName = item.TagName.ToUpper();
                if (tagName == "SPAN" && item.OuterHtml.Contains("nickName") && item.OuterHtml.Contains("class="))
                {
                    accountModel.NickName = item.InnerText;
                    accountModel.IsLogined = true;
                }else if (tagName == "IMG")
                {
                    var content = item.OuterHtml.Replace("&amp;", "&");

                    const string pattern = @"src=""?(?<ImageUrl>[^""]*username=(?<UserName>[^&]*)[^""]*)""? ?";
                    var match = Regex.Match(content, pattern);
                    if (match.Success)
                    {
                        //accountModel.UserName = match.Groups["UserName"].Value;
                        accountModel.AvatarUrl = (accountModel.Host + match.Groups["ImageUrl"].Value);
                    }

                }
            }

            return accountModel;
        }




        #region "获取WebBrowser指定的图片"

        /// <summary>   
        /// 获取WebBrowser指定的图片   
        /// </summary>   
        /// <param name="webBrowser">需要获取图片的WebBrowser</param>   
        /// <param name="imgID">指定的图片的id(优先查找指定id)</param>   
        /// <param name="imgSrc">指定的图片的src，支持模糊查询</param>   
        /// <param name="imgAlt">指定的图片的src， 支持模糊查询</param>   
        /// <returns></returns>   
        public static Image GetImage(ref WebBrowser webBrowser, String imgID, String imgSrc, String imgAlt)
        {
            var doc = (HTMLDocument)webBrowser.Document.DomDocument;
            var body = (HTMLBody)doc.body;
            var rang = (IHTMLControlRange)body.createControlRange();
            IHTMLControlElement img;

            // 如果没有图片的ID,通过Src或Alt中的关键字来取   
            if (imgID.Length == 0)
            {
                Int32 imgNum = GetPicIndex(ref webBrowser, ref imgSrc, ref imgAlt);

                if (imgNum == -1)
                    return null;

                img = (IHTMLControlElement)webBrowser.Document.Images[imgNum].DomElement;
            }
            else
                img = (IHTMLControlElement)webBrowser.Document.All[imgID].DomElement;

            rang.add(img);
            rang.execCommand("Copy", false, null);
            Image regImg = Clipboard.GetImage();
            Clipboard.Clear();
            return regImg;
        }

        /// <summary>   
        /// 获取WebBrowser指定图片的索引   
        /// </summary>   
        /// <param name="webBrowser">指定的WebBrowser</param>   
        /// <param name="imgSrc">指定的图片src，支持模糊查询</param>   
        /// <param name="imgAlt">指定的图片alt，支持模糊查询</param>   
        /// <returns></returns>   
        private static Int32 GetPicIndex(ref WebBrowser webBrowser, ref String imgSrc, ref String imgAlt)
        {
            IHTMLImgElement img;

            // 获取所有的Image元素   
            for (Int32 i = 0; i < webBrowser.Document.Images.Count; i++)
            {
                img = (IHTMLImgElement)webBrowser.Document.Images[i].DomElement;

                if (imgAlt.Length == 0)
                {
                    if (img.src.IndexOf(imgSrc) >= 0)
                        return i;
                }
                else
                {
                    if (imgSrc.Length == 0)
                    {
                        // 当imgSrc为空时，只匹配imgAlt   
                        if (img.alt.IndexOf(imgAlt) >= 0)
                            return i;
                    }
                    else
                    {
                        // 当imgSrc不为空时，匹配imgAlt和imgSrc任意一个   
                        if (img.alt.IndexOf(imgAlt) >= 0 || img.src.IndexOf(imgSrc) >= 0)
                            return i;
                    }
                }
            }
            return -1;
        }
        #endregion






















        ////public static string TaskWaitGetImage(AccountModel accountModel)
        ////{
        ////    var task = new Task<string>(() => GetImage(accountModel.AvatarUrl, accountModel.NickName, accountModel.LoginCookies));
        ////    task.Start();
        ////    task.Wait();

        ////    return task.Result.ToString();
        ////}

        ////////public static CookieContainer StringToCookie(string domain, string cookieString)
        ////////{
        ////////    cookieString = cookieString.Replace(",", "%2C");
        ////////    var myCookieContainer = new CookieContainer();
        ////////    var arrCookie = cookieString.Split(';');
        ////////    foreach (var str in arrCookie)
        ////////    {
        ////////        var cookieNameValue = str.Split('=');

        ////////        var oDomain = domain;
        ////////        if (cookieNameValue[0].Trim() == "pgv_pvi" || cookieNameValue[0].Trim() == "pgv_si" ||
        ////////            cookieNameValue[0].Trim() == "wxstaytime"
        ////////            || cookieNameValue[0].Trim() == "pt2gguin"
        ////////            || cookieNameValue[0].Trim() == "RK"
        ////////            || cookieNameValue[0].Trim() == "ptcz"
        ////////            || cookieNameValue[0].Trim() == "uin_cookie"
        ////////            || cookieNameValue[0].Trim() == "euin_cookie"
        ////////            || cookieNameValue[0].Trim() == "pgv_pvid"
        ////////            || cookieNameValue[0].Trim() == "o_cookie"
        ////////            || cookieNameValue[0].Trim() == "ac")
        ////////        {
        ////////            oDomain = "qq.com";
        ////////        }
        ////////        else
        ////////        {
        ////////            oDomain = "wx.qq.com";
        ////////        }
        ////////        var cookie = new Cookie(cookieNameValue[0].Trim(), cookieNameValue[1].Trim()) { Domain = oDomain };
        ////////        myCookieContainer.Add(cookie);
        ////////    }

        ////////    return myCookieContainer;
        ////////}

        ////public static string StringToCookie2(string cookieString)
        ////{
        ////    var ret = new List<string>();
        ////    var arrCookie = cookieString.Split(';');
        ////    foreach (var str in arrCookie)
        ////    {
        ////        var cookieNameValue = str.Split('=');
        ////        if (cookieNameValue[0].Trim() == "pt2gguin"
        ////            || cookieNameValue[0].Trim() == "RK"
        ////            || cookieNameValue[0].Trim() == "ptcz"
        ////            || cookieNameValue[0].Trim() == "uin_cookie"
        ////            || cookieNameValue[0].Trim() == "euin_cookie"
        ////            || cookieNameValue[0].Trim() == "pgv_pvid"
        ////            || cookieNameValue[0].Trim() == "o_cookie"
        ////            || cookieNameValue[0].Trim() == "ac")
        ////        {

        ////        }
        ////        else
        ////        {
        ////            ret.Add(string.Format("{0}={1}", cookieNameValue[0], cookieNameValue[1]));
        ////        }

        ////    }

        ////    return string.Join(";", ret);
        ////}

        ////public static string GetImage(string imageUrl, string userName, string cookieString)
        ////{
        ////    var path = ApplicationDeployment.IsNetworkDeployed ? ApplicationDeployment.CurrentDeployment.DataDirectory : Environment.CurrentDirectory;
        ////    path = string.Format(@"{0}\Avatars\", path);

        ////    var filePath = string.Format("{0}{1}.png", path, userName);

        ////    cookieString = StringToCookie2(cookieString);

        ////    try
        ////    {
        ////        var httpWebRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
        ////        httpWebRequest.Method = "GET";
        ////        httpWebRequest.Accept = "text/html, application/xhtml+xml, */*";
        ////        httpWebRequest.UserAgent = "Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25";
        ////        httpWebRequest.Headers.Add("Cache-Control: no-cache");
        ////        httpWebRequest.Headers.Add(string.Format("Cookie: {0}", cookieString));
        ////        //httpWebRequest.CookieContainer = StringToCookie(domain, cookieString);
        ////        httpWebRequest.AllowAutoRedirect = false;
        ////        httpWebRequest.Timeout = 60000;
        ////        httpWebRequest.ContentType = "application/x-www-form-urlencoded";

        ////        var webResponse = httpWebRequest.GetResponse();
        ////        var responseStream = webResponse.GetResponseStream();

        ////        var bitmap = new Bitmap(responseStream);
        ////        bitmap.Save(filePath, ImageFormat.Png);
        ////    }
        ////    catch (Exception ex)
        ////    {
                
        ////        //throw ex;
        ////        return string.Format("{0}HH_HAVENT81.png", path);
        ////    }

        ////    return path;
        ////}



    }

}
